package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.Map;

/**
 * @author lirl
 * @date 2021/2/5 23:06
 * 全局异常处理类
 * 通过“basePackages”能够说明处理哪些路径下的异常。
 *
 */
//@RestControllerAdvice()
@Slf4j
public class GulimallExceptionControllerAdvice {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R  handlerValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题:{},问题是:{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap =Maps.newHashMap();
        bindingResult.getFieldErrors().forEach(item->{
            errorMap.put(item.getField(), item.getDefaultMessage()) ;
        });

        return  R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", errorMap);
    }
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("未知异常:{},异常类型:{}",throwable.getMessage(),throwable.getClass());
        return R.error(BizCodeEnum.UNKNOW_EXEPTION.getCode(),BizCodeEnum.UNKNOW_EXEPTION.getMsg());
    }

}
